<template>
  <div class="page-box">
    <ContentWrap>
      <el-form
        ref="formRef"
        v-loading="formLoading"
        :model="formData"
        :rules="formRules"
        label-width="200"
      >
        <div>
          <div class="title">企业基本信息:</div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="企业名称" prop="companyName">
                <el-input
                  :maxlength="50"
                  v-model="formData.companyName"
                  placeholder="请输入企业名称"
                  @blur="validCustomerName"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="统一社会信用代码" prop="socialCreditCode">
                <el-input
                  :maxlength="50"
                  v-model="formData.socialCreditCode"
                  placeholder="请输入统一社会信用代码"
                  @blur="validSocialCreditCode"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="法定代表人" prop="legalPerson">
                <el-input
                  :maxlength="20"
                  v-model="formData.legalPerson"
                  placeholder="请输入法定代表人姓名"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="法人身份证号" prop="legalPersonId">
                <el-input
                  :maxlength="18"
                  v-model="formData.legalPersonId"
                  placeholder="请输入法人身份证号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户银行" prop="depositBank">
                <el-input
                  :maxlength="50"
                  v-model="formData.depositBank"
                  placeholder="请输入开户银行"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="银行账号" prop="bankAccount">
                <el-input
                  :maxlength="25"
                  v-model="formData.bankAccount"
                  placeholder="请输入银行账号"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="注册地址">
                <div class="address-box">
                  <div>
                    <el-form-item label="省" prop="provinceAddress" class="address-item">
                      <el-select
                        v-model="formData.provinceAddress"
                        placeholder="请选择省"
                        @change="changeProvince"
                        style="width: 120px"
                      >
                        <el-option
                          v-for="dict in pCTlist"
                          :key="dict.id"
                          :label="dict.name"
                          :value="dict.id"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="市" prop="cityAddress" class="address-item">
                      <el-select
                        v-model="formData.cityAddress"
                        placeholder="请选择市"
                        @change="changeCity"
                        style="width: 120px"
                      >
                        <el-option
                          v-for="dict in citylist"
                          :key="dict.id"
                          :label="dict.name"
                          :value="dict.id"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="区县" prop="countyAddress" class="address-item">
                      <el-select
                        v-model="formData.countyAddress"
                        placeholder="请选择县/区"
                        @change="changeCounty"
                        style="width: 120px"
                      >
                        <el-option
                          v-for="dict in arealist"
                          :key="dict.id"
                          :label="dict.name"
                          :value="dict.id"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="街道" prop="townsAddress" class="address-item">
                      <el-select
                        v-model="formData.townsAddress"
                        placeholder="请选择街道"
                        @change="changeTowns"
                        style="width: 120px"
                      >
                        <el-option
                          v-for="dict in streetlist"
                          :key="dict.id"
                          :label="dict.name"
                          :value="dict.id"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                  <div class="detail-address">
                    <el-form-item label="详细地址" prop="simpleAddress" class="detail-address-item">
                      <el-input
                        :maxlength="50"
                        v-model="formData.simpleAddress"
                        placeholder="请输入详细地址"
                      />
                    </el-form-item>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div>
          <div class="title">联系人:</div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="联系人" prop="contactPerson">
                <el-input
                  :maxlength="20"
                  v-model="formData.contactPerson"
                  placeholder="请输入联系人"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证号" prop="contactId">
                <el-input
                  :maxlength="18"
                  v-model="formData.contactId"
                  placeholder="请输入身份证号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人电话" prop="contactPhone">
                <el-input
                  :maxlength="11"
                  v-model="formData.contactPhone"
                  placeholder="请输入联系人电话"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="登录账号" prop="userAccount">
                <el-input
                  :maxlength="16"
                  v-model="formData.userAccount"
                  placeholder="请输入登录账号"
                  @blur="validUserAccount"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div>
          <div class="title">附件信息:</div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="营业执照" prop="businessLicense">
                <UploadImg v-model="formData.businessLicense" :limit="1" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="法人身份证（正）" prop="frontLegalPersonId">
                <UploadImg v-model="formData.frontLegalPersonId" :limit="1" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="法人身份证（反）" prop="backLegalPersonId">
                <UploadImg v-model="formData.backLegalPersonId" :limit="1" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="委托书" prop="powerAttorney">
                <UploadImg v-model="formData.powerAttorney" :limit="1" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人身份证（正）" prop="frontContactPersonId">
                <UploadImg v-model="formData.frontContactPersonId" :limit="1" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人身份证（反）" prop="backContactPersonId">
                <UploadImg v-model="formData.backContactPersonId" :limit="1" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div>
          <div class="title">合同上传:</div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="合同">
                <UploadImgs :limit="10" v-model="formData.contractFiles" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div class="footer">
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm()">取 消</el-button>
      </div>
    </ContentWrap>
  </div>
</template>
<script lang="ts" setup>
import * as AreaApi from '@/api/system/area'
import * as register from '@/api/register'
import * as customer from '@/api/customer'
import { useRouter } from 'vue-router'
import { cloneDeep } from 'lodash-es'

const formRef = ref()
const { t } = useI18n()
const router = useRouter()
const message = useMessage()
const formLoading = ref(false)
const pCTlist: Record<string, any> = ref([])
const citylist: Record<string, any> = ref([])
const arealist: Record<string, any> = ref([])
const streetlist: Record<string, any> = ref([])
const isValidID = (rule, idCard, callback) => {
  const regex =
    /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/
  if (regex.test(idCard)) {
    callback()
  } else {
    callback(new Error('身份证号不合法'))
  }
}
const isValidPhoneNumber = (rule, phone, callback) => {
  if (/^1\d{10}$/.test(phone)) {
    callback()
  } else {
    callback(new Error('手机号码不正确'))
  }
}

const valiAccount = (rule, accout, callback) => {
  if (/^[a-zA-Z0-9]{6,16}$/.test(accout)) {
    callback()
  } else {
    callback(new Error('账号必须满足6-16位数字或字母组合的字符串'))
  }
}

const formData: Record<string, any> = ref({
  companyName: undefined,
  socialCreditCode: undefined,
  legalPerson: undefined,
  legalPersonId: undefined,
  depositBank: undefined,
  bankAccount: undefined,
  provinceAddress: undefined,
  cityAddress: undefined,
  countyAddress: undefined,
  townsAddress: undefined,
  simpleAddress: undefined,
  contactPerson: undefined,
  contactId: undefined,
  contactPhone: undefined,
  businessLicense: undefined,
  powerAttorney: undefined,
  frontLegalPersonId: undefined,
  backLegalPersonId: undefined,
  frontContactPersonId: undefined,
  backContactPersonId: undefined,
  contractFiles: [],
  userAccount: undefined
})
const formRules = reactive({
  companyName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
  socialCreditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: 'blur' }],
  legalPerson: [{ required: true, message: '法定代表人不能为空', trigger: 'blur' }],
  legalPersonId: [
    { required: true, message: '法人身份证号不能为空', trigger: 'blur' },
    { validator: isValidID, trigger: 'blur' }
  ],
  depositBank: [{ required: true, message: '开户银行不能为空', trigger: 'blur' }],
  bankAccount: [
    { required: true, message: '银行账号不能为空', trigger: 'blur' },
    { min: 10, max: 25, message: '银行账号长度10-25位', trigger: 'blur' },
    { pattern: /^\d+$/, message: '银行账号必须是数字', trigger: 'blur' }
  ],
  provinceAddress: [{ required: true, message: '省份不能为空', trigger: 'change' }],
  cityAddress: [{ required: true, message: '城市不能为空', trigger: 'change' }],
  countyAddress: [{ required: true, message: '县区不能为空', trigger: 'change' }],
  townsAddress: [{ required: true, message: '街道不能为空', trigger: 'change' }],
  simpleAddress: [{ required: true, message: '详细地址不能为空', trigger: 'change' }],
  contactPerson: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  contactId: [
    { required: true, message: '联系人身份证号不能为空', trigger: 'blur' },
    { validator: isValidID, trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '联系人电话不能为空', trigger: 'blur' },
    { validator: isValidPhoneNumber, trigger: 'blur' }
  ],
  userAccount: [
    { required: true, message: '登录账号不能为空', trigger: 'blur' },
    { validator: valiAccount, trigger: 'blur' }
  ],
  businessLicense: [{ required: true, message: '营业执照不能为空', trigger: 'change' }],
  powerAttorney: [{ required: true, message: '委托书不能为空', trigger: 'change' }],
  frontLegalPersonId: [{ required: true, message: '法人身份证正面不能为空', trigger: 'change' }],
  backLegalPersonId: [{ required: true, message: '法人身份证反面不能为空', trigger: 'change' }],
  frontContactPersonId: [
    { required: true, message: '联系人身份证正面不能为空', trigger: 'change' }
  ],
  backContactPersonId: [{ required: true, message: '联系人身份证反面不能为空', trigger: 'change' }]
})

const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  registerCustomer()
}

const registerCustomer = async () => {
  formLoading.value = true
  try {
    const data = cloneDeep(formData.value)
    data['businessLicense'] = data.businessLicense || {}
    data['powerAttorney'] = data.powerAttorney || {}
    data['frontLegalPersonId'] = data.frontLegalPersonId || {}
    data['backLegalPersonId'] = data.backLegalPersonId || {}
    data['frontContactPersonId'] = data.frontContactPersonId || {}
    data['backContactPersonId'] = data.backContactPersonId || {}
    await register.registerCustomer({
      ...data,
      ...{
        detailAddress: getDetailAddress(),
        contractFiles: (data.contractFiles || []).map((e: Record<string, any>) =>
          e?.response?.data ? e?.response?.data : e
        )
      }
    })
    message.success(t('common.createSuccess'))
    router.push({ path: '/submitSuccess' })
  } finally {
    formLoading.value = false
  }
}

const getDetailAddress = () => {
  const provinceAddress = pCTlist.value.find((e) => e.id === formData.value.provinceAddress)?.name
  const cityAddress = citylist.value.find((e) => e.id === formData.value.cityAddress)?.name
  const countyAddress = arealist.value.find((e) => e.id === formData.value.countyAddress)?.name
  const townsAddress = streetlist.value.find((e) => e.id === formData.value.townsAddress)?.name
  return `${provinceAddress || ''}${cityAddress || ''}${countyAddress || ''}${townsAddress || ''}${
    formData.value.simpleAddress || ''
  }`
}

const cancelForm = () => {
  router.push('/registerJump')
}

const getAreaTree = async () => {
  pCTlist.value = await AreaApi.getAreaTree()
}

const changeProvince = (id) => {
  formData.value.cityAddress = undefined
  formData.value.countyAddress = undefined
  formData.value.townsAddress = undefined
  formData.value.simpleAddress = undefined
  citylist.value = pCTlist.value.find((e) => e.id === id)?.children || []
}

const changeCity = (id) => {
  formData.value.countyAddress = undefined
  formData.value.townsAddress = undefined
  formData.value.simpleAddress = undefined
  arealist.value = citylist.value.find((e) => e.id === id)?.children || []
}

const changeCounty = (id) => {
  formData.value.townsAddress = undefined
  formData.value.simpleAddress = undefined
  streetlist.value = arealist.value.find((e) => e.id === id)?.children || []
}

const changeTowns = () => {
  formData.value.simpleAddress = undefined
}

const validCustomerName = async () => {
  if (!formData.value.companyName) {
    return
  }
  const data = {
    companyName: formData.value.companyName
  }
  if (formData.value.id) {
    data['id'] = formData.value.id
  }
  await customer.validCustomerName(data)
}

const validSocialCreditCode = async () => {
  if (!formData.value.socialCreditCode) {
    return
  }
  const data = {
    socialCreditCode: formData.value.socialCreditCode
  }
  if (formData.value.id) {
    data['id'] = formData.value.id
  }
  await customer.validSocialCreditCode(data)
}

const validUserAccount = async () => {
  if (!formData.value.userAccount) {
    return
  }
  const data = {
    userAccount: formData.value.userAccount
  }
  if (formData.value.id) {
    data['id'] = formData.value.id
  }
  await customer.validUserAccount(data)
}

onMounted(() => {
  getAreaTree()
})
</script>
<style lang="scss" scoped>
.page-box {
  padding: 0 100px;
  height: 100%;
  overflow-y: auto;

  .title {
    font-weight: bold;
    margin-bottom: 20px;
  }
}

.address-box {
  display: flex;
  width: 100%;

  > div {
    display: flex;
  }

  > .detail-address {
    flex: 1;
  }

  .detail-address-item {
    width: 100%;
  }
}

.footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep form div.el-form-item__content div.address-item label {
  width: 70px !important;
}

:deep form div.el-form-item__content div.detail-address > div label {
  width: 100px !important;
}
</style>
